package com.qyhl.module_activities.act.live;

import android.app.Activity;
import androidx.core.content.ContextCompat;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.common.ActUrl;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.basiclib.utils.network.model.ApiResult;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.act.TeleVoteBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import es.dmoral.toasty.Toasty;

public class TeleVoteAdapter extends CommonAdapter<TeleVoteBean.EntityListBean> {

    private final int SUPPORT = 1;
    private final int OPPOSE = 2;
    private final int NO = 0;
    private Activity activity;
    private String actId;
    private String linkId;

    public TeleVoteAdapter(Activity activity, List<TeleVoteBean.EntityListBean> datas, String actId, String linkId) {
        super(activity, R.layout.act_televote_view, datas);
        this.activity = activity;
        this.linkId = linkId;
        this.actId = actId;
    }

    @Override
    protected void convert(ViewHolder holder, TeleVoteBean.EntityListBean bean, int position) {
        holder.setText(R.id.title, bean.getName());
        holder.setText(R.id.approve_text, bean.getSupportName());
        holder.setText(R.id.oppose_text, bean.getOpposeName());
        holder.setText(R.id.approve_button, bean.getSupportName());
        holder.setText(R.id.oppose_button, bean.getOpposeName());

        changeWidth((TextView) holder.getView(R.id.approve_text), (TextView) holder.getView(R.id.oppose_text));

        if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_NOLOGIN) {
            setVisibleStatus(holder, false);
            setButtonImg(holder, NO);

        } else if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_BEFORE) {
            setVisibleStatus(holder, false);
            setButtonImg(holder, NO);

        } else if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_AFTER) {
            setVisibleStatus(holder, true);
            setButtonImg(holder, getVoteStatus(bean));
            calculation(holder, bean);

        } else if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_BEGIN) {
            int voteStatus = getVoteStatus(bean);
            if (voteStatus == NO) {
                setVisibleStatus(holder, false);
            } else {
                setVisibleStatus(holder, true);
                calculation(holder, bean);
            }
            setButtonImg(holder, voteStatus);
        }
        holder.setTag(R.id.approve_button, position);
        holder.setTag(R.id.oppose_button, position);
        holder.setOnClickListener(R.id.approve_button, clickListener);
        holder.setOnClickListener(R.id.oppose_button, clickListener);
    }

    private void calculation(ViewHolder holder, TeleVoteBean.EntityListBean bean) {
        DecimalFormat decimalFormat = new DecimalFormat("0.##");
        holder.setText(R.id.approve_progress, decimalFormat.format(bean.getSupportPer() * 100) + "%");
        holder.setText(R.id.oppose_progress, decimalFormat.format(bean.getOpposePer() * 100) + "%");
        changeWidth((TextView) holder.getView(R.id.approve_progress), (TextView) holder.getView(R.id.oppose_progress));
        ((ProgressBar) holder.getView(R.id.approve_probar)).setProgress((int) Math.round(bean.getSupportPer() * 100));
        ((ProgressBar) holder.getView(R.id.oppose_probar)).setProgress((int) Math.round(bean.getOpposePer() * 100));
    }

    private void changeWidth(TextView view, TextView view1) {
        int width = (int) Math.max(view.getPaint().measureText(view.getText().toString()),
                view1.getPaint().measureText(view1.getText().toString()));
        view.getLayoutParams().width = width;
        view1.getLayoutParams().width = width;
    }

    private int getVoteStatus(TeleVoteBean.EntityListBean bean) {
        if (bean.getUserSupport() == 0 && bean.getUserOppose() == 0) {
            return NO;
        } else {
            //已经投过票了
            if (bean.getUserSupport() == 1) {
                return SUPPORT;
            } else {
                return OPPOSE;
            }
        }
    }

    /**
     * @param status 0 没投过  1 投了支持   2 投了反对
     */
    private void setButtonImg(ViewHolder holder, int status) {
        TextView support = holder.getView(R.id.approve_button);
        TextView oppose = holder.getView(R.id.oppose_button);
        switch (status) {
            case NO:
                support.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(activity, R.drawable.def_approve_img), null, null);
                oppose.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(activity, R.drawable.def_oppose_img), null, null);
                break;
            case SUPPORT:
                support.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(activity, R.drawable.approve_img), null, null);
                oppose.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(activity, R.drawable.no_oppose_img), null, null);
                break;
            case OPPOSE:
                support.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(activity, R.drawable.no_approve_img), null, null);
                oppose.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(activity, R.drawable.oppose_img), null, null);
                break;
            default:
        }
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_NOLOGIN) {
                RouterManager.routerLogin(activity, 0);

            } else if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_AFTER) {
                Toasty.normal(activity, "活动已结束", Toast.LENGTH_SHORT).show();

            } else if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_BEFORE) {
                Toasty.normal(activity, "活动未开始", Toast.LENGTH_SHORT).show();

            } else if (TeleVotePresenter.STATUS == TeleVotePresenter.STATUS_BEGIN) {
                final int position = (int) v.getTag();
                final TeleVoteBean.EntityListBean bean = getDatas().get(position);
                if (getVoteStatus(bean) == NO) {
                    if (bean.isCanVote()) {
                        bean.setCanVote(false);

                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (v.getId() == R.id.approve_button) {
                                        vote(1, position);
                                    } else if (v.getId() == R.id.oppose_button) {
                                        vote(0, position);
                                    }
                                } else {
                                    TeleVotePresenter.STATUS = TeleVotePresenter.STATUS_NOLOGIN;
                                    notifyDataSetChanged();
                                    Toasty.normal(activity, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                    RouterManager.routerLogin(activity, 0);
                                    bean.setCanVote(true);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });

                    }
                } else {
                    Toasty.normal(activity, "您已投票", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    private void setVisibleStatus(ViewHolder holder, boolean status) {
        holder.setVisible(R.id.oppose_probar, status);
        holder.setVisible(R.id.approve_probar, status);
        holder.setVisible(R.id.approve_progress, status);
        holder.setVisible(R.id.oppose_progress, status);
    }


    private void vote(final int isSupport, final int position) {
        if (NetUtil.isNetworkAvalible(activity)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String time = sdf.format(new Date());
            String code = "Z5" + time + "I2863";
            String url = ActUrl.GET_TELETEXT_VOTE + "?timestamp=" + time;

            EasyHttp.post(url)
                    .upBytes(DESedeUtil.encryptMode(code, "sActId=" + actId + "&linkId=" + linkId + "&linkType=0&sActEntId="
                            + getDatas().get(position).getId() + "&isSupport=" + isSupport
                            + "&voter=" + CommonUtils.getInstance().getUserName()
                    ))
                    .isDecrypt(true)
                    .decryptKet(code)
                    .execute(new SimpleCallBack<String>() {
                        @Override
                        public void onError(ApiException e) {
                            Toasty.normal(activity, "网络异常，加载失败！").show();
                            getDatas().get(position).setCanVote(true);
                        }

                        @Override
                        public void onSuccess(String s) {
                            ApiResult re = new Gson().fromJson(s, ApiResult.class);
                            if (re.getCode() == 200 || re.getCode() == 202) {
                                TeleVoteBean.EntityListBean entityListBean = getDatas().get(position);
                                if (isSupport == 1) {
                                    entityListBean.setUserSupport(1);
                                    entityListBean.setSupport(entityListBean.getSupport() + 1);
                                } else {
                                    entityListBean.setUserOppose(1);
                                    entityListBean.setOppose(entityListBean.getOppose() + 1);
                                }
                                entityListBean.setSupportPer((double) entityListBean.getSupport() / ((double) entityListBean.getSupport() + (double) entityListBean.getOppose()));
                                entityListBean.setOpposePer((double) entityListBean.getOppose() / ((double) entityListBean.getSupport() + (double) entityListBean.getOppose()));
                                notifyItemChanged(position);
                            } else {
                                Toasty.normal(activity, re.getCode() + re.getMessage()).show();
                            }
                            getDatas().get(position).setCanVote(true);
                        }
                    });
        } else {
            Toasty.normal(activity, "请检查网络...").show();
            getDatas().get(position).setCanVote(true);
        }
    }
}
